package strategy

import (
	"fmt"
	"strings"
	"super/constant"
	"super/db"
	"super/global"

	"github.com/duke-git/lancet/strutil"
)

type T2jStrategy struct {
}

func (t2js T2jStrategy) Init() {
	if db.Dao == nil {
		err := db.InitDB()
		if err != nil {
			fmt.Println(err)
			fmt.Print("super>")
			return
		}
	}
	global.CurStatus = constant.T2j
	fmt.Print("t2j>")
}

func (t2js T2jStrategy) Handle(str string) {
	table2java(str)
	fmt.Print("t2j>")
}

func table2java(table string) {
	var tableComment string
	err := db.Dao.Get(&tableComment, "SELECT TABLE_COMMENT FROM information_schema.TABLES WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", table, db.TableSchema)
	if err != nil {
		fmt.Println(1, err)
		return
	}
	rows, err := db.Dao.Query("select COLUMN_NAME ,COLUMN_TYPE ,COLUMN_COMMENT,COLUMN_KEY from information_schema.`COLUMNS` c where TABLE_NAME = ? AND TABLE_SCHEMA = ? ", table, db.TableSchema)
	if err != nil {
		fmt.Println(2, err)
		return
	}
	fmt.Printf(
		`
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.tdh.lawsuit.common.entity.function.FunctionBaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.time.LocalDateTime;
	
/**
 * %s
 */
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("%s")
public class %s{`, tableComment, table, strutil.UpperFirst(strutil.CamelCase(strings.ToLower(table))))

	fmt.Println()

	for rows.Next() {
		var columnName, columnType, columnComment, columnKey string
		rows.Scan(&columnName, &columnType, &columnComment, &columnKey)
		var attr = `
	/**
	 * %s
	 */
	@Table%s(value = "%s")
	private %s %s;
	`
		var ct string = "String"
		var lowerColumnType = strings.ToLower(columnType)
		if strings.Contains(lowerColumnType, "int") || strings.Contains(lowerColumnType, "num") || strings.Contains(lowerColumnType, "dec") {
			ct = "Integer"
		} else if strings.Contains(lowerColumnType, "date") || strings.Contains(lowerColumnType, "time") {
			ct = "LocalDateTime"
		}
		var annotation string = "Field"
		if columnKey == "PRI" {
			annotation = "Id"
		}
		fmt.Printf(attr, columnComment, annotation, columnName, ct, strutil.CamelCase(strings.ToLower(columnName)))
	}
	fmt.Println()
	fmt.Println("}")
}
